package com.cq.hd.app.controller;

import com.cq.hd.app.vo.BusinessInviteVo;
import com.cq.hd.common.annotation.LoginUser;
import com.cq.hd.common.entity.AppLoginUser;
import com.cq.hd.common.entity.BusinessInfo;
import com.cq.hd.common.entity.UserInfo;
import com.cq.hd.common.enums.ResponseEnums;
import com.cq.hd.common.enums.biz.AgentStateEnum;
import com.cq.hd.common.enums.biz.InviteTypeEnum;
import com.cq.hd.common.pagination.Page;
import com.cq.hd.common.response.Result;
import com.cq.hd.common.response.ResultGenerator;
import com.cq.hd.common.response.Throw;
import com.cq.hd.common.utils.BeanUtils;
import com.cq.hd.common.utils.StringUtils;
import com.cq.hd.member.api.TbBusinessAgentApi;
import com.cq.hd.member.api.TbBusinessApi;
import com.cq.hd.member.api.dto.*;
import com.cq.hd.member.api.vo.*;
import com.cq.hd.product.api.TbActiveApi;
import com.cq.hd.product.api.dto.BusinessHomeActivePageDto;
import com.cq.hd.product.api.vo.BusinessHomeActivePageVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

@Slf4j
@RestController
@RequestMapping("/business")
@Api(tags = "商家相关接口")
public class BusinessController extends BaseController {

    @Autowired
    private TbBusinessApi businessApi;

    @Autowired
    private TbActiveApi activeApi;

    @Autowired
    private TbBusinessAgentApi businessAgentApi;

    @ApiOperation(value = "获取活动发布次数: 这个接口只返回次数，商户版上线后，可以去掉，使用下面[getActiveLimit]的接口")
    @ApiResponse(response = Integer.class, code = 200, message = "接口返回对象参数")
    @GetMapping("/getActiveCount")
    public Result<Integer> getActiveCount(@ApiIgnore @LoginUser AppLoginUser appLoginUser) {
        Long businessId = 0L;
        BusinessInfo businessInfo = appLoginUser.getUserInfo().getBusinessInfo();
        if (businessInfo != null) {
            businessId = businessInfo.getId();
        }

        BusinessVo businessVo = businessApi.getActiveCount(appLoginUser.getUserId(), businessId).unpack();
        if (businessVo == null) {
            Throw.isBusinessException(ResponseEnums.BUSINESS_ACCESS_DENIED);
        }

        return ResultGenerator.success(businessVo.getActiveCount());
    }

    @ApiOperation(value = "获取商家发布活动限制参数")
    @ApiResponse(response = BusinessActiveLimitVo.class, code = 200, message = "接口返回对象参数")
    @GetMapping("/getActiveLimit")
    public Result<BusinessActiveLimitVo> getActiveLimit(@ApiIgnore @LoginUser AppLoginUser appLoginUser) {
        Long businessId = 0L;
        BusinessInfo businessInfo = appLoginUser.getUserInfo().getBusinessInfo();
        if (businessInfo != null) {
            businessId = businessInfo.getId();
        }

        BusinessVo businessVo = businessApi.getActiveCount(appLoginUser.getUserId(), businessId).unpack();
        if (businessVo == null) {
            Throw.isBusinessException(ResponseEnums.BUSINESS_ACCESS_DENIED);
        }
        BusinessActiveLimitVo businessActiveLimitVo = new BusinessActiveLimitVo();
        BeanUtils.copyProperties(businessVo, businessActiveLimitVo);

        return ResultGenerator.success(businessActiveLimitVo);
    }

    @ApiOperation(value = "商家邀请商户")
    @ApiResponse(response = InviteMerchantVo.class, code = 200, message = "接口返回对象参数")
    @PostMapping("/inviteMerchant")
    public Result<InviteMerchantVo> inviteMerchant(@ApiIgnore @LoginUser AppLoginUser appLoginUser) {
        BusinessInviteDto businessInviteDto = new BusinessInviteDto();
        // 邀请类型：1-邀请商户，2-邀请经纪人
        businessInviteDto.setType(InviteTypeEnum.INVITE_MERCHANT.getValue());

        BusinessInfo businessInfo = appLoginUser.getUserInfo().getBusinessInfo();
        if (businessInfo != null) {
            businessInviteDto.setBusinessId(businessInfo.getId());
            businessInviteDto.setInviteCode(businessInfo.getInviteCode());
            businessInviteDto.setBusinessName(businessInfo.getBusinessName());
            businessInviteDto.setBusinessShortName(businessInfo.getBusinessShortName());
            businessInviteDto.setLogo(businessInfo.getLogo());
        }
        businessInviteDto.setUserId(appLoginUser.getUserId());

        return businessApi.invite(businessInviteDto);
    }

    @ApiOperation(value = "商家解绑商户")
    @ApiImplicitParam(name = "businessMerchantUnBindDto", value = "实体", required = true, paramType = "body", dataType = "BusinessMerchantUnBindDto")
    @PostMapping("/unBindMerchant")
    public Result<Boolean> unBindMerchant(@ApiIgnore @LoginUser AppLoginUser appLoginUser, @RequestBody BusinessMerchantUnBindDto businessMerchantUnBindDto) {
        BusinessInfo businessInfo = appLoginUser.getUserInfo().getBusinessInfo();
        if (businessInfo != null) {
            businessMerchantUnBindDto.setBusinessId(businessInfo.getId());
            businessMerchantUnBindDto.setBusinessShortName(businessInfo.getBusinessShortName());
        }

        businessMerchantUnBindDto.setUserId(appLoginUser.getUserId());
        return businessApi.unBindMerchant(businessMerchantUnBindDto);
    }

    @ApiOperation(value = "关联商户列表（供添加活动商品调用）")
    @ApiResponse(response = RelationMerchantPageVo.class, code = 200, message = "接口返回对象参数")
    @GetMapping("/pageRelationMerchant")
    public Result<Page<RelationMerchantPageVo>> pageRelationMerchant(@ApiIgnore @LoginUser AppLoginUser appLoginUser, RelationMerchantPageDto relationMerchantPageDto) {
        BusinessInfo businessInfo = appLoginUser.getUserInfo().getBusinessInfo();
        if (businessInfo != null) {
            relationMerchantPageDto.setId(businessInfo.getId());
        }
        relationMerchantPageDto.setUserId(appLoginUser.getUserId());

        return businessApi.pageRelationMerchant(relationMerchantPageDto);
    }


    /**
     * 1、点击商家头像，查看商家主页，需要传商家id，且返回是否订阅该商家
     * 2、点击商家主页分享链接，查看商家主页，需要传商家id，且返回是否订阅该商家，如果用户没登陆，则返回未订阅
     * 3、商家自己查看自己商家主页，不用传商家id
     * 4、商家点击商家头像/商家主页分享链接，查看商家主页，根据token中的商家id和传的商家比对，如果一致，则表示商家自己查看自己的商家主页
     */
    @ApiOperation(value = "商家主页")
    @ApiImplicitParam(name = "id", value = "商家id", required = true, paramType = "query", dataType = "Long")
    @ApiResponse(response = BusinessHomePageVo.class, code = 200, message = "接口返回对象参数")
    @GetMapping("/getHomePage")
    public Result<BusinessHomePageVo> getHomePage(Long id) {
        Long userId = 0L;
        if (id == null || id <= 0) {
            Throw.isBusinessException("请选择查看的商家");
        }

        AppLoginUser appLoginUser = getAppLoginUser();
        if(appLoginUser != null){
            userId = appLoginUser.getUserId();
        }

        return businessApi.getHomePage(id, userId);
    }

    /**
     * 1、商家查看自己商家主页，显示全部的活动列表，删除，修改，分享，成交量和金额等统计数据
     * 2、已登录的用户查看商家主页，显示进行中和已结束的活动列表，分享
     * 3、未登录的用户查看商家主页（与用户点击商家分享主页链接相同），显示进行中和已结束的活动列表，分享，除了查看活动详情外的操作，都需要登录
     * 4、经纪人受邀查看商家主页，需要登录，显示进行中和已结束的活动列表，分享，可推广的活动(只显示进行中的活动)
     */
    @ApiOperation(value = "商家主页活动列表")
    @ApiResponse(response = BusinessHomeActivePageVo.class, code = 200, message = "接口返回对象参数")
    @GetMapping("/pageHomeActive")
    public Result<Page<BusinessHomeActivePageVo>> pageActive(BusinessHomeActivePageDto businessHomeActivePageDto) {
        AppLoginUser appLoginUser = getAppLoginUser();
        Long businessId = businessHomeActivePageDto.getBusinessId();
        if (businessId == null || businessId <= 0) {
            Throw.isBusinessException("请选择查看的商家");
        }

        // 类型：1-默认，2-可分销的活动
        Integer type = businessHomeActivePageDto.getType();
        // 如果查询的是可分销的活动，则必须要登录
        if (type != null && type == 2) {
            if (appLoginUser == null) {
                Throw.isBusinessException(ResponseEnums.USER_ACCESS_DENIED);
            }
            businessHomeActivePageDto.setAgentId(appLoginUser.getUserId());
        }

        if (appLoginUser != null) {
            BusinessInfo businessInfo = appLoginUser.getUserInfo().getBusinessInfo();
            if (businessInfo != null) {
                businessHomeActivePageDto.setOwnBusinessId(businessInfo.getId());
            }

            businessHomeActivePageDto.setUserId(appLoginUser.getUserId());
        }

        return activeApi.pageHomeActive(businessHomeActivePageDto);
    }

    @ApiOperation(value = "编辑商家主页")
    @ApiImplicitParam(name = "updateHomePageDto", value = "实体", required = true, paramType = "body", dataType = "UpdateHomePageDto")
    @PutMapping("/updateHomePage")
    public Result<Boolean> updateHomePage(@ApiIgnore @LoginUser AppLoginUser appLoginUser, @RequestBody UpdateHomePageDto updateHomePageDto) {
        BusinessInfo businessInfo = appLoginUser.getUserInfo().getBusinessInfo();
        if (businessInfo != null) {
            updateHomePageDto.setId(businessInfo.getId());
        }
        updateHomePageDto.setUserId(appLoginUser.getUserId());

        return businessApi.updateHomePage(updateHomePageDto);
    }

    @ApiOperation(value = "分享商家主页")
    @ApiImplicitParam(name = "businessShareDto", value = "商家id", required = true, paramType = "body", dataType = "BusinessShareDto")
    @ApiResponse(response = BusinessShareVo.class, code = 200, message = "接口返回对象参数")
    @PostMapping("/shareHomePage")
    public Result<BusinessShareVo> shareHomePage(@ApiIgnore @LoginUser AppLoginUser appLoginUser, @RequestBody BusinessShareDto businessShareDto) {
        businessShareDto.setUserId(appLoginUser.getUserId());
        return businessApi.shareHomePage(businessShareDto);
    }

    @ApiOperation(value = "商家邀请经纪人/一级经纪人邀请二级经纪人")
    @ApiResponse(response = InviteMerchantVo.class, code = 200, message = "接口返回对象参数")
    @ApiImplicitParam(name = "groupId", value = "分组id", required = false, paramType = "body", dataType = "Long")
    @PostMapping("/inviteAgent")
    public Result<InviteMerchantVo> inviteAgent(@ApiIgnore @LoginUser AppLoginUser appLoginUser, Long groupId) {
        BusinessInviteDto businessInviteDto = new BusinessInviteDto();
        // 邀请类型：1-邀请商户，2-邀请经纪人，3-一级经纪人邀请二级经纪人

        BusinessInfo businessInfo = appLoginUser.getUserInfo().getBusinessInfo();
        if (businessInfo != null) {
            businessInviteDto.setBusinessId(businessInfo.getId());
            businessInviteDto.setInviteCode(businessInfo.getInviteCode());
            businessInviteDto.setBusinessName(businessInfo.getBusinessName());
            businessInviteDto.setBusinessShortName(businessInfo.getBusinessShortName());
            businessInviteDto.setLogo(businessInfo.getLogo());
            businessInviteDto.setType(InviteTypeEnum.INVITE_AGENT.getValue());
        } else {
            businessInviteDto.setType(InviteTypeEnum.INVITE_SUB_AGENT.getValue());

            UserInfo userInfo = appLoginUser.getUserInfo();
            if (userInfo.getAgentState().equals(AgentStateEnum.CLOSE.getValue()) || userInfo.getAgentId() != 0L) {
                Throw.isBusinessException("你不是一级经纪人，无法邀请二级经纪人");
            }
            businessInviteDto.setInviteCode(userInfo.getInviteCode());
            businessInviteDto.setBusinessName(userInfo.getRealName());
            businessInviteDto.setBusinessShortName(userInfo.getNickName());
            businessInviteDto.setLogo(userInfo.getAvatar());
        }
        businessInviteDto.setUserId(appLoginUser.getUserId());
        businessInviteDto.setGroupId(groupId);

        return businessApi.invite(businessInviteDto);
    }

    @ApiOperation(value = "商家解除绑定经纪人分销关系")
    @ApiImplicitParam(name = "businessAgentUnBindDto", value = "实体", required = true, paramType = "body", dataType = "BusinessAgentUnBindDto")
    @PostMapping("/unBindAgent")
    public Result<Boolean> unBindAgent(@ApiIgnore @LoginUser AppLoginUser appLoginUser, @RequestBody BusinessAgentUnBindDto businessAgentUnBindDto) {
        businessAgentUnBindDto.setUserId(appLoginUser.getUserId());
        BusinessInfo businessInfo = appLoginUser.getUserInfo().getBusinessInfo();
        if (businessInfo != null) {
            businessAgentUnBindDto.setBusinessId(businessInfo.getId());
        }
        return businessAgentApi.unBind(businessAgentUnBindDto);
    }

    @ApiOperation(value = "经纪人解除与商家的分销关系")
    @ApiImplicitParam(name = "businessAgentUnBindDto", value = "实体", required = true, paramType = "body", dataType = "BusinessAgentUnBindDto")
    @PostMapping("/unBindMyBusiness")
    public Result<Boolean> unBindMyBusiness(@ApiIgnore @LoginUser AppLoginUser appLoginUser, @RequestBody BusinessAgentUnBindDto businessAgentUnBindDto) {
        businessAgentUnBindDto.setId(appLoginUser.getUserId());
        return businessAgentApi.unBind(businessAgentUnBindDto);
    }

    @ApiOperation(value = "角色管理主页")
    @ApiResponse(response = BusinessAgentIndexVo.class, code = 200, message = "接口返回对象参数")
    @GetMapping("/businessAgentIndex")
    public Result<BusinessAgentIndexVo> businessAgentIndex(@ApiIgnore @LoginUser AppLoginUser appLoginUser) {
        Long businessId = 0L;
        UserInfo userInfo = appLoginUser.getUserInfo();
        BusinessInfo businessInfo = userInfo.getBusinessInfo();
        if (businessInfo != null) {
            businessId = businessInfo.getId();
        }

        BusinessAgentIndexDto businessAgentIndexDto = new BusinessAgentIndexDto();
        businessAgentIndexDto.setUserId(appLoginUser.getUserId());
        businessAgentIndexDto.setAgentState(appLoginUser.getUserInfo().getAgentState());
        businessAgentIndexDto.setBusinessId(businessId);
        businessAgentIndexDto.setAgentLevel(userInfo.getAgentLevel());
        return businessAgentApi.businessAgentIndex(businessAgentIndexDto);
    }

    @ApiOperation(value = "我的经纪人分页条件列表")
    @ApiResponse(response = MyAgentPageVo.class, code = 200, message = "接口返回对象参数")
    @GetMapping("/pageMyAgent")
    public Result<Page<MyAgentPageVo>> pageMyAgent(@ApiIgnore @LoginUser AppLoginUser appLoginUser, MyAgentPageDto myAgentPageDto) {
        BusinessIdAgentIdDto businessIdAgentIdDto = getBusinessIdAnAgentId(appLoginUser);
        myAgentPageDto.setBusinessId(businessIdAgentIdDto.getBusinessId());
        myAgentPageDto.setAgentId(businessIdAgentIdDto.getAgentId());
        return businessAgentApi.pageMyAgent(myAgentPageDto);
    }

    @ApiOperation(value = "我的策划人分页条件列表")
    @ApiResponse(response = MyBusinessPageVo.class, code = 200, message = "接口返回对象参数")
    @GetMapping("/pageMyBusiness")
    public Result<Page<MyBusinessPageVo>> pageMyBusiness(@ApiIgnore @LoginUser AppLoginUser appLoginUser, MyBusinessPageDto myBusinessPageDto) {
        myBusinessPageDto.setUserId(appLoginUser.getUserId());
        return businessAgentApi.pageMyBusiness(myBusinessPageDto);
    }

    @ApiOperation(value = "经纪人专属佣金设置")
    @ApiImplicitParam(name = "businessAgentCommissionSaveDto", value = "实体", required = true, paramType = "body", dataType = "BusinessAgentCommissionSaveDto")
    @PutMapping("/saveAgentCommission")
    public Result<Boolean> saveAgentCommission(@ApiIgnore @LoginUser AppLoginUser appLoginUser,
                                               @RequestBody BusinessAgentCommissionSaveDto businessAgentCommissionSaveDto) {
        BusinessIdAgentIdDto businessIdAgentIdDto = getBusinessIdAnAgentId(appLoginUser);
        businessAgentCommissionSaveDto.setBusinessId(businessIdAgentIdDto.getBusinessId());
        businessAgentCommissionSaveDto.setAgentId(businessIdAgentIdDto.getAgentId());
        return businessAgentApi.saveAgentCommission(businessAgentCommissionSaveDto);
    }

    @ApiOperation(value = "已设置佣金和未设置佣金经纪人列表")
    @ApiResponse(response = BusinessAgentCommissionPageVo.class, code = 200, message = "接口返回对象参数")
    @GetMapping("/pageAgentCommission")
    public Result<Page<BusinessAgentCommissionPageVo>> pageAgentCommission(@ApiIgnore @LoginUser AppLoginUser appLoginUser,
                                                                           BusinessAgentCommissionPageDto businessAgentCommissionPageDto) {
        BusinessIdAgentIdDto businessIdAgentIdDto = getBusinessIdAnAgentId(appLoginUser);
        businessAgentCommissionPageDto.setBusinessId(businessIdAgentIdDto.getBusinessId());
        businessAgentCommissionPageDto.setAgentId(businessIdAgentIdDto.getAgentId());
        return businessAgentApi.pageAgentCommission(businessAgentCommissionPageDto);
    }

    private BusinessIdAgentIdDto getBusinessIdAnAgentId(AppLoginUser appLoginUser) {
        BusinessIdAgentIdDto businessIdAgentIdDto = new BusinessIdAgentIdDto();
        BusinessInfo businessInfo = appLoginUser.getUserInfo().getBusinessInfo();
        if (businessInfo != null) {
            businessIdAgentIdDto.setBusinessId(businessInfo.getId());
        } else {
            businessIdAgentIdDto.setAgentId(appLoginUser.getUserId());
        }
        return businessIdAgentIdDto;
    }

    @ApiOperation(value = "通过邀请商家邀请码获取商家部分信息")
    @ApiImplicitParam(name = "inviteCode", value = "商家邀请码", required = true, paramType = "String", dataType = "String")
    @GetMapping("/getByInviteCode")
    public Result<BusinessInviteVo> getBusinessByInviteCode(String inviteCode) {
        if (StringUtils.isBlank(inviteCode)) {
            Throw.isBusinessException("邀请码不能为空");
        }

        BusinessInviteVo businessInviteVo = new BusinessInviteVo();
        BusinessPageVo businessPageVo = businessApi.getByInviteCode(inviteCode).unpack();
        if (businessPageVo != null) {
            BeanUtils.copyProperties(businessPageVo, businessInviteVo);
        }

        return ResultGenerator.success(businessInviteVo);
    }

    @ApiOperation(value = "分享海报是否显示商家头像开关")
    @ApiImplicitParam(name = "businessPosterShowAvatarDto", value = "分享海报是否显示商家头像开关: 1是 2否", required = true, paramType = "body", dataType = "BusinessPosterShowAvatarDto")
    @PostMapping("/updatePosterShowAvatarState")
    public Result<Integer> updatePosterShowAvatarState(@ApiIgnore @LoginUser AppLoginUser appLoginUser, @RequestBody BusinessPosterShowAvatarDto businessPosterShowAvatarDto) {
        BusinessInviteDto businessInviteDto = new BusinessInviteDto();
        // 邀请类型：1-邀请商户，2-邀请经纪人
        businessInviteDto.setType(InviteTypeEnum.INVITE_MERCHANT.getValue());

        BusinessInfo businessInfo = appLoginUser.getUserInfo().getBusinessInfo();
        if (businessInfo == null) {
            Throw.isBusinessException(ResponseEnums.BUSINESS_ACCESS_DENIED);
        }

        return businessApi.updatePosterShowAvatarState(businessInfo.getId(), businessPosterShowAvatarDto.getPosterShowAvatarState());
    }
}
